package edu.zsc.utils;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import edu.zsc.control.ElevatorRequest;
import lombok.extern.slf4j.Slf4j;

import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ExcelUtils {

    private ExcelUtils() {
    }

    public static <T> List<T> readExcel(String fileName, Class<T> clazz) {

        String filePath = getFilePath(fileName);
        ObjectListener<T> listener = new ObjectListener<>();
        EasyExcel.read(filePath, ElevatorRequest.class, listener).sheet().doRead();
        return listener.list;
    }

    private static String getFilePath(String fileName) {
        ClassLoader classLoader = ExcelUtils.class.getClassLoader();
        URL resource = classLoader.getResource(fileName);
        String filePath = "";
        try {
            assert resource != null;
            filePath = URLDecoder.decode(resource.getPath(), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return filePath;
    }

    static class ObjectListener<T> extends AnalysisEventListener<T> {

        private List<T> list = new ArrayList<>();

        @Override
        public void invoke(T t, AnalysisContext analysisContext) {
            list.add(t);
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
            log.info("加载数据完成，总共加载{}条数据", list.size());
        }
    }
}
